package com.hm.ipay.service.impl;

import com.hm.ipay.IStatusMessage;
import com.hm.ipay.MessageProperties;
import com.hm.ipay.ServiceException;
import com.hm.ipay.dao.AccountTransactionRecordMapper;
import com.hm.ipay.dao.UserAccountMapper;
import com.hm.ipay.domain.AccountEarnings;
import com.hm.ipay.domain.AccountRelationshipMap;
import com.hm.ipay.domain.AccountTotal;
import com.hm.ipay.domain.result.ExceptionMsg;
import com.hm.ipay.domain.result.ResponseData;
import com.hm.ipay.domain.result.ResponseDataList;
import com.hm.ipay.entity.AccountTransactionRecord;
import com.hm.ipay.entity.UserAccount;
import com.hm.ipay.service.AccountService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    UserAccountMapper userAccountMapper;

    @Autowired
    AccountTransactionRecordMapper accountTransactionRecordMapper;

    @Autowired
    private MessageProperties config;

    @Override
    public ResponseData userAccountInfo(Long id) {
        UserAccount account = userAccountMapper.selectByPrimaryKey(id);
        if (account == null) {
            return new ResponseData(ExceptionMsg.UserNotFound);
        } else {
            return new ResponseData(ExceptionMsg.SUCCESS, account);
        }
    }

    @Override
    public ResponseData tranRecordList(Long userId, Integer transactionType) {
        Map<String, Number> map = new HashMap<>();
        map.put("userId", userId);
        map.put("transactionType", transactionType);
        List<AccountTransactionRecord> list = accountTransactionRecordMapper.transactionRecordList(map);
        return new ResponseData(ExceptionMsg.SUCCESS, list);
    }

    @Override
    public ResponseDataList bgTranRecordList(Integer limit, Integer offset, String userName, Integer transactionType) {
        Map map = new HashMap();
        map.put("userName", userName);
        map.put("transactionType", transactionType);
        if (StringUtils.isEmpty(limit)) {
            limit = 20;
        }
        if (StringUtils.isEmpty(offset)) {
            offset = 0;
        }
        map.put("limit", limit);
        map.put("offset", offset);
        List<UserAccount> records = accountTransactionRecordMapper.selectAllRecord(map);
        int record_count = accountTransactionRecordMapper.countAllRecord(map);
        return new ResponseDataList(ExceptionMsg.SUCCESS, limit, offset, record_count, records);
    }

    @Override
    public ResponseDataList userAccountList(Integer limit, Integer offset, String userName, String tel) {
        Map map = new HashMap();
        map.put("userName", userName);
        map.put("tel", tel);
        if (StringUtils.isEmpty(limit)) {
            limit = 20;
        }
        if (StringUtils.isEmpty(offset)) {
            offset = 0;
        }
        map.put("limit", limit);
        map.put("offset", offset);
        List<UserAccount> accounts = userAccountMapper.selectAllAccount(map);
        int account_count = userAccountMapper.countAllAccount(map);
        return new ResponseDataList(ExceptionMsg.SUCCESS, limit, offset, account_count, accounts);
    }

    @Override
    public ResponseData frozenAccount(Long userId) {
        UserAccount account = userAccountMapper.selectByPrimaryKey(userId);
        if (account == null) {
            return new ResponseData(ExceptionMsg.UserNotFound);
        } else {
            account.setActivateStatus((byte)2);
            userAccountMapper.updateByPrimaryKeySelective(account);
            return new ResponseData(ExceptionMsg.SUCCESS);
        }
    }

    @Override
    public ResponseData accountThaw(Long userId) {
        UserAccount account = userAccountMapper.selectByPrimaryKey(userId);
        if (account == null) {
            return new ResponseData(ExceptionMsg.UserNotFound);
        } else {
            account.setActivateStatus((byte)0);
            userAccountMapper.updateByPrimaryKeySelective(account);
            return new ResponseData(ExceptionMsg.SUCCESS);
        }
    }

    @Override
    public ResponseData accountTotal() {
        AccountTotal total = userAccountMapper.accountTotal();
        return new ResponseData(ExceptionMsg.SUCCESS, total);
    }

    @Override
    public ResponseData accountRelationship(Long userId) {
        AccountRelationshipMap result = new AccountRelationshipMap();
        UserAccount account = userAccountMapper.selectByPrimaryKey(userId);
        List<UserAccount> down_lv1;
        List<UserAccount> down_lv2;
        List<AccountEarnings> down_lv1e = new ArrayList<>();
        List<AccountEarnings> down_lv2e = new ArrayList<>();
        if (account == null) {
            return new ResponseData(ExceptionMsg.UserNotFound);
        } else {
            UserAccount upLv1 = userAccountMapper.selectByPrimaryKey(account.getPrimaryBeneficiary());
            UserAccount upLv2 = userAccountMapper.selectByPrimaryKey(account.getSecondaryBeneficiary());
            down_lv1 = userAccountMapper.primaryList(userId);
            down_lv2 = userAccountMapper.secondaryList(userId);
            Map map = new HashMap();
            BigDecimal earnings = new BigDecimal(0);
            AccountEarnings accountEarnings = null;
            for (int i = 0; i < down_lv1.size(); i++) {
                map.clear();
                map.put("userId", userId);
                map.put("opposite", down_lv1.get(i).getId());
                earnings = accountTransactionRecordMapper.selectEarnings(map);
                accountEarnings = new AccountEarnings();
                accountEarnings.setAccount(down_lv1.get(i));
                accountEarnings.setEarnings(earnings);
                down_lv1e.add(accountEarnings);
            }
            for (int j = 0; j < down_lv2.size(); j++) {
                map.clear();
                map.put("userId", userId);
                map.put("opposite", down_lv2.get(j).getId());
                earnings = accountTransactionRecordMapper.selectEarnings(map);
                accountEarnings = new AccountEarnings();
                accountEarnings.setAccount(down_lv2.get(j));
                accountEarnings.setEarnings(earnings);
                down_lv2e.add(accountEarnings);
            }
            result.setUp_lv1(upLv1);
            result.setUp_lv2(upLv2);
            result.setDown_lv1(down_lv1e);
            result.setDown_lv2(down_lv2e);
            return new ResponseData(ExceptionMsg.SUCCESS, result);
        }
    }

    @Override
    public ResponseData setAccountInfo(UserAccount account) {
        UserAccount user = userAccountMapper.selectByPrimaryKey(account.getId());
        user.setBalance(account.getBalance());
        user.setCreditBalance(account.getCreditBalance());
        userAccountMapper.updateByPrimaryKeySelective(user);
        return new ResponseData(ExceptionMsg.SUCCESS);
    }

    /**
     *  上传文件的种类
     *  1.用户头像           ipay-resources/user-profile/时间
     *  2.游戏列表图         ipay-resources/game-list/时间
     *  3.游戏描述图 或 视频  ipay-resources/game-describe/时间
     *  4.游戏结果图         ipay-resources/game-result/时间
     */
    @Override
    public Map<String, Object> uploadPicture(MultipartFile file, String dirType) throws ServiceException {
        try {
            Map<String, Object> resMap = new HashMap<>();
            String[] IMAGE_TYPE = config.getImageType().split(",");
            String path = null;
            boolean flag = false;
            for (String type : IMAGE_TYPE) {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                resMap.put("result", IStatusMessage.SystemStatus.SUCCESS.getMessage());
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                // 获得文件类型
                String fileType = file.getContentType();
                // 获得文件后缀名称
                String imageName = fileType.substring(fileType.indexOf("/") + 1);
                // 原名称
                String oldFileName = file.getOriginalFilename();
                // 新名称
                String newFileName = uuid + "." + imageName;
                // 年月日文件夹
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String basedir = sdf.format(new Date());
                // 进行压缩(大于4M)
                if (0 > 1) {  // 不压缩
                //if (file.getSize() > config.getFileSize()) {
                    // 重新生成
                    String newUUID = UUID.randomUUID().toString().replaceAll("-", "");
                    newFileName = newUUID + "." + imageName;
                    path = config.getUpPath() + "/" + dirType + "/" + basedir + "/" + newUUID + "." + imageName;
                    // 如果目录不存在则创建目录
                    File oldFile = new File(path);
                    if (!oldFile.exists()) {
                        oldFile.mkdirs();
                    }
                    file.transferTo(oldFile);
                    // 压缩图片
                    Thumbnails.of(oldFile).scale(config.getScaleRatio()).toFile(path);
                    // 显示路径
                    resMap.put("path", "/" + dirType + "/" + basedir + "/" + newUUID + "." + imageName);
                } else {
                    path = config.getUpPath() + "/" + dirType + "/" + basedir + "/" + uuid + "." + imageName;
                    // 如果目录不存在则创建目录
                    File uploadFile = new File(path);
                    if (!uploadFile.exists()) {
                        uploadFile.mkdirs();
                    }
                    file.transferTo(uploadFile);
                    // 显示路径
                    resMap.put("path", "/" + dirType + "/" + basedir + "/" + uuid + "." + imageName);
                }
                resMap.put("oldFileName", oldFileName);
                resMap.put("newFileName", newFileName);
                resMap.put("fileSize", file.getSize());
            } else {
                resMap.put("result", "图片格式不正确,支持png|jpg|jpeg");
            }
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public ResponseData setAccountProfile(Long userId, String profile) {
        UserAccount account = userAccountMapper.selectByPrimaryKey(userId);
        if (account == null) {
            return new ResponseData(ExceptionMsg.UserNotFound);
        } else {
            account.setProfilePhoto(profile);
            userAccountMapper.updateByPrimaryKeySelective(account);
            return new ResponseData(ExceptionMsg.SUCCESS);
        }
    }
}
